import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { LOADING_STATES, THEMES } from '../constants'

/**
 * 全局状态管理
 */
export const useGlobalStore = defineStore('global', () => {
  // 应用状态
  const appInitialized = ref(false)
  const currentTheme = ref(THEMES.LIGHT)
  const sidebarCollapsed = ref(false)
  const fullscreen = ref(false)
  
  // 加载状态
  const globalLoading = ref(false)
  const loadingText = ref('')
  const loadingProgress = ref(0)
  
  // 错误状态
  const hasError = ref(false)
  const errorMessage = ref('')
  const errorCode = ref('')
  
  // 用户状态
  const user = ref({
    id: null,
    name: '访客用户',
    avatar: '',
    permissions: []
  })
  
  // 应用配置
  const config = ref({
    maxFileSize: 10 * 1024 * 1024, // 10MB
    pageSize: 20,
    autoSave: true,
    animationEnabled: true
  })
  
  // 最近使用的文件
  const recentFiles = ref([])
  
  // 通知列表
  const notifications = ref([])
  
  // 计算属性
  const isLoading = computed(() => globalLoading.value)
  const isDarkTheme = computed(() => currentTheme.value === THEMES.DARK)
  const hasRecentFiles = computed(() => recentFiles.value.length > 0)
  const unreadNotifications = computed(() => 
    notifications.value.filter(n => !n.read).length
  )
  
  // 应用初始化
  const initializeApp = async () => {
    try {
      setGlobalLoading(true, '初始化应用...')
      
      // 加载用户偏好设置
      await loadUserPreferences()
      
      // 加载最近文件
      await loadRecentFiles()
      
      // 应用主题
      applyTheme(currentTheme.value)
      
      appInitialized.value = true
      setGlobalLoading(false)
    } catch (error) {
      setError('应用初始化失败', error.message)
      setGlobalLoading(false)
    }
  }
  
  // 加载用户偏好设置
  const loadUserPreferences = async () => {
    try {
      const saved = localStorage.getItem('powerbi_preferences')
      if (saved) {
        const preferences = JSON.parse(saved)
        currentTheme.value = preferences.theme || THEMES.LIGHT
        config.value = { ...config.value, ...preferences.config }
      }
    } catch (error) {
      console.warn('加载用户偏好设置失败:', error)
    }
  }
  
  // 保存用户偏好设置
  const saveUserPreferences = () => {
    try {
      const preferences = {
        theme: currentTheme.value,
        config: config.value
      }
      localStorage.setItem('powerbi_preferences', JSON.stringify(preferences))
    } catch (error) {
      console.error('保存用户偏好设置失败:', error)
    }
  }
  
  // 加载最近文件
  const loadRecentFiles = async () => {
    try {
      const saved = localStorage.getItem('powerbi_recent_files')
      if (saved) {
        recentFiles.value = JSON.parse(saved)
      }
    } catch (error) {
      console.warn('加载最近文件失败:', error)
    }
  }
  
  // 添加最近文件
  const addRecentFile = (file) => {
    const existingIndex = recentFiles.value.findIndex(f => f.path === file.path)
    
    if (existingIndex !== -1) {
      // 如果文件已存在，移到最前面
      recentFiles.value.splice(existingIndex, 1)
    }
    
    recentFiles.value.unshift({
      ...file,
      lastOpened: new Date().toISOString()
    })
    
    // 限制最近文件数量
    if (recentFiles.value.length > 10) {
      recentFiles.value = recentFiles.value.slice(0, 10)
    }
    
    // 保存到本地存储
    try {
      localStorage.setItem('powerbi_recent_files', JSON.stringify(recentFiles.value))
    } catch (error) {
      console.error('保存最近文件失败:', error)
    }
  }
  
  // 清除最近文件
  const clearRecentFiles = () => {
    recentFiles.value = []
    localStorage.removeItem('powerbi_recent_files')
  }
  
  // 设置全局加载状态
  const setGlobalLoading = (loading, text = '加载中...', progress = 0) => {
    globalLoading.value = loading
    loadingText.value = text
    loadingProgress.value = progress
  }
  
  // 更新加载进度
  const updateLoadingProgress = (progress) => {
    loadingProgress.value = Math.max(0, Math.min(100, progress))
  }
  
  // 设置错误状态
  const setError = (message, code = '') => {
    hasError.value = true
    errorMessage.value = message
    errorCode.value = code
  }
  
  // 清除错误状态
  const clearError = () => {
    hasError.value = false
    errorMessage.value = ''
    errorCode.value = ''
  }
  
  // 切换主题
  const toggleTheme = () => {
    currentTheme.value = isDarkTheme.value ? THEMES.LIGHT : THEMES.DARK
    applyTheme(currentTheme.value)
    saveUserPreferences()
  }
  
  // 应用主题
  const applyTheme = (theme) => {
    if (theme === THEMES.DARK) {
      document.documentElement.classList.add('dark')
    } else {
      document.documentElement.classList.remove('dark')
    }
  }
  
  // 切换侧边栏
  const toggleSidebar = () => {
    sidebarCollapsed.value = !sidebarCollapsed.value
  }
  
  // 切换全屏
  const toggleFullscreen = () => {
    if (!document.fullscreenElement) {
      document.documentElement.requestFullscreen()
      fullscreen.value = true
    } else {
      document.exitFullscreen()
      fullscreen.value = false
    }
  }
  
  // 添加通知
  const addNotification = (notification) => {
    const newNotification = {
      id: Date.now().toString(),
      timestamp: new Date().toISOString(),
      read: false,
      ...notification
    }
    
    notifications.value.unshift(newNotification)
    
    // 限制通知数量
    if (notifications.value.length > 50) {
      notifications.value = notifications.value.slice(0, 50)
    }
    
    return newNotification.id
  }
  
  // 标记通知为已读
  const markNotificationRead = (id) => {
    const notification = notifications.value.find(n => n.id === id)
    if (notification) {
      notification.read = true
    }
  }
  
  // 清除所有通知
  const clearNotifications = () => {
    notifications.value = []
  }
  
  // 更新配置
  const updateConfig = (key, value) => {
    config.value[key] = value
    saveUserPreferences()
  }
  
  // 批量更新配置
  const updateConfigs = (updates) => {
    Object.assign(config.value, updates)
    saveUserPreferences()
  }
  
  // 重置应用状态
  const resetApp = () => {
    appInitialized.value = false
    globalLoading.value = false
    hasError.value = false
    clearError()
    clearRecentFiles()
    clearNotifications()
  }
  
  return {
    // 状态
    appInitialized,
    currentTheme,
    sidebarCollapsed,
    fullscreen,
    globalLoading,
    loadingText,
    loadingProgress,
    hasError,
    errorMessage,
    errorCode,
    user,
    config,
    recentFiles,
    notifications,
    
    // 计算属性
    isLoading,
    isDarkTheme,
    hasRecentFiles,
    unreadNotifications,
    
    // 方法
    initializeApp,
    loadUserPreferences,
    saveUserPreferences,
    addRecentFile,
    clearRecentFiles,
    setGlobalLoading,
    updateLoadingProgress,
    setError,
    clearError,
    toggleTheme,
    applyTheme,
    toggleSidebar,
    toggleFullscreen,
    addNotification,
    markNotificationRead,
    clearNotifications,
    updateConfig,
    updateConfigs,
    resetApp
  }
})



